package com.yingside.net.chat01;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.List;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class ClientFrame extends JFrame {

	private JPanel panel;
	private JScrollPane jspLeft,jspRight;
	private JList nameList;
	private JTextArea chatTxt;
	private JTextField input;
	private JButton btnSend;
	private String name;
	private DefaultListModel model;

	private Socket s= null;
	private BufferedReader br = null;
	private PrintWriter out = null;
	private boolean flag = true;
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
//					ClientFrame frame = new ClientFrame();
//					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public ClientFrame(String name) {
		this.name = name;
		this.setTitle("聊天窗口:[当前用户:" + this.name + "]");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(400, 100, 550, 400);
		nameList = new JList();
		nameList.setFixedCellWidth(100);
		jspLeft = new JScrollPane(nameList);
		chatTxt = new JTextArea();
		jspRight = new JScrollPane(chatTxt);
		model = new DefaultListModel();
		nameList.setModel(model);

		panel = new JPanel();
		input = new JTextField(20);
		btnSend = new JButton("发送");

		btnSend.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String word = input.getText();
				if(word == null || word.equals("")){
					return;
				}

				//群聊和私聊的判断
				List values = nameList.getSelectedValuesList();
				boolean isAll = false;
				String us = "to:";
				if(values.size() <= 0) isAll = true;
				for(Object o : values){
					if(o.toString().equals("所有人")){
						isAll = true;
						break;
					}else{
						us += o.toString() + ",";
					}
				}

				//根据选择的人名发送信息
				if(isAll){
					out.println(us + "all" + ":end" + word);
				}else{
					out.println(us + ":end" + word);
				}
				input.setText("");
			}
		});

		panel.add(input);
		panel.add(btnSend);

		this.add(jspLeft,BorderLayout.WEST);
		this.add(jspRight);
		this.add(panel,BorderLayout.SOUTH);
		connect();
		this.setVisible(true);
	}

	public void connect(){
		try {
			s = new Socket("127.0.0.1",8888);
			out = new PrintWriter(s.getOutputStream(),true);
			br = new BufferedReader(new InputStreamReader(s.getInputStream()));

			out.println(this.name);

			new Thread(new ClientThread()).start();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void handleList(String str){
		String users = str.substring("users:".length());
		String [] us = users.split(",");
		model.removeAllElements();
		model.addElement("所有人");
		for(String u : us){
			model.addElement(u);
		}
	}

	public void receive() throws IOException{
		//接收服务器回馈的信息
		String str = br.readLine();
		//客户端这边接收服务器的信息，如果是disconnect就直接退出循环关闭
		if(str.equalsIgnoreCase("disconnect")){
			flag = false;
		}

		//每个用户登录，在界面List中加入名字
		if(str.startsWith("users:")){
			handleList(str);
			return;
		}

		chatTxt.setText(chatTxt.getText() + str + "\n");
	}

	private class ClientThread implements Runnable{

		@Override
		public void run() {
			try {
				while(true){
					if(!flag) break;
					receive();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally{
				if(s != null){
					try {
						s.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}

		}

	}

}
